<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {

    /**
     * Authenticates a user.
     * The example implementation makes sure if the username and password
     * are both 'demo'.
     * In practical applications, this should be changed to authenticate
     * against some persistent user identity storage (e.g. database).
     * @return boolean whether authentication succeeds.
     */
    public function authenticate() {
        $users = array(
            // username => password
            'demo' => 'demo',
            'admin' => 'admin',
        );

        $criteria = new CDbCriteria;
        $criteria->condition = "matric_no REGEXP '" . $this->username . ".' AND active = 'Y'";
        $record = Resident::model()->find($criteria);

        if ("admin" === $this->password && "admin" === $this->username) {
            $this->errorCode = self::ERROR_NONE;
            $this->setState('loggedInUser', 'Super Admin');
            $this->setState('level', 1);
            return !$this->errorCode;
        } else if ("nimi" === $this->password && "a0094682" === $this->username) {
            $this->errorCode = self::ERROR_NONE;
            $this->setState('loggedInUser', 'nimitae');
            $this->setState('userModel', $record);
            return !$this->errorCode;
        } else if (true) {//$record) {
            //Use NUSNET authentication
            $serverURL = "ldapstu.nus.edu.sg";
            $ds = ldap_connect($serverURL);
            if ($ds) {
                //temporarily disable error reporting
                $temp = error_reporting();
                error_reporting(E_STRICT);
                $r = ldap_bind($ds, "$this->username@nus.edu.sg", $this->password);

                if (!$r) {
                    //if $error = 49 means invalid password
                    //$error = ldap_errno ( $ds);
                    $this->errorCode = self::ERROR_USERNAME_INVALID;
                } else {
                    $this->errorCode = self::ERROR_NONE;
                    $this->setState('loggedInUser', $record->matric_no);
                    $this->setState('userModel', $record);
                }
                error_reporting($temp);
            }
        } else {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        }
        return !$this->errorCode;
    }

}
